package util

import (
	"github.com/beego/beego/v2/server/web"
	"os"
	"path/filepath"
	"strings"
)

// JsonRes 是响应结构体
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// Uploader 结构体
type Uploader struct {
	MaxSize     int64
	ValidExtMap map[string]bool
}

// NewUploader 创建一个新的 Uploader 实例
func NewUploader(maxSize int64, ValidExtMap []string) *Uploader {
	extMap := make(map[string]bool)
	for _, ext := range ValidExtMap {
		extMap[strings.ToLower(ext)] = true
	}
	return &Uploader{
		MaxSize:     maxSize,
		ValidExtMap: extMap,
	}
}

// Upload 处理文件上传
func (u *Uploader) Upload(c *web.Controller, fileField string, saveDir string) {
	file, header, err := c.GetFile(fileField)
	if err != nil {
		c.Data["json"] = JsonRes{Code: 500, Msg: "文件获取失败", Data: nil}
		c.ServeJSON()
		return
	}
	defer file.Close()

	// 文件大小验证
	if header.Size > u.MaxSize {
		c.Data["json"] = JsonRes{Code: 500, Msg: "文件过大，请重新上传", Data: nil}
		c.ServeJSON()
		return
	}

	// 文件格式验证
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !u.ValidExtMap[suffix] {
		c.Data["json"] = JsonRes{Code: 500, Msg: "格式错误，只支持指定格式", Data: nil}
		c.ServeJSON()
		return
	}

	// 创建保存目录
	if err = os.MkdirAll(saveDir, os.ModePerm); err != nil {
		c.Data["json"] = JsonRes{Code: 500, Msg: "无法创建目录", Data: nil}
		c.ServeJSON()
		return
	}

	// 保存文件
	path := filepath.Join(saveDir, header.Filename) // static/img/ + header.Filename
	err = c.SaveToFile(fileField, path)
	if err != nil {
		c.Data["json"] = JsonRes{Code: 500, Msg: "上传失败", Data: nil}
		c.ServeJSON()
		return
	}

	// 返回成功信息
	imgSrc := "http://localhost:8080/" + header.Filename
	c.Data["json"] = JsonRes{Code: 200, Msg: "上传成功", Data: imgSrc}
	c.ServeJSON()
}
